<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ColumnCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:column {table} {column}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * @return void
     * @throws Exception
     */
    public function handle(): void
    {
        $table = $this->argument('table');
        $column = $this->argument('column');
        $table = humpToLine($table);
        $result = DB::select("show tables like '$table'");
        if (empty($result)) die('表不存在');
        $file = database_path('migrations/sql/' . $table . '.sql');
        if (!is_file($file)) die('sql文件不存在');
        $handle = file($file);
        $arr = [];
        $has = $index = 0;
        $left = '';
        for ($i = 3; $i < count($handle); $i++) {
            $str = trim(strtr($handle[$i], [PHP_EOL => '']));
            if (!str_starts_with($str, '`')) break;
            else if (str_starts_with($str, "`$column`")) {
                $result = DB::select("show columns from `$table`");
                foreach ($result as $v) {
                    if ($v->Field === $column) {
                        $has = 1;
                        break;
                    }
                }
                $index = $i - 3;
                if (isset($arr[$index - 1])) {
                    $end = strpos($arr[$index - 1], '`', 1);
                    $left = substr($arr[$index - 1], 0, $end + 1);
                }
            }
            $arr[] = $str;
        }
        if ($index === 0) die('sql文件字段不存在');
        $type = $has === 0 ? 'add' : 'modify';
        $sql = "alter table `$table` $type column " . $arr[$index];
        $sql = substr($sql, 0, -1);
        if (strlen($left) === 0) $sql .= ' first';
        else $sql .= ' after ' . $left;
        DB::select($sql);
    }
}
